package com.hulk.rpc.transport.server.rest.handler;

import com.hulk.rpc.config.common.HulkConstants;
import com.hulk.rpc.filter.RestServerFilter;
import com.hulk.rpc.invoke.ServiceInvokeFactory;
import com.hulk.rpc.serialize.impl.json.JsonMapper;
import com.hulk.rpc.transport.server.rest.codec.RestHttResponseEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @Author: xuxukang
 * @Date: 2019/9/17 0017 15:50
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class NettyRestChannelInitializer extends ChannelInitializer<SocketChannel> {

  private final ServiceInvokeFactory invokerFactory;
  private final JsonMapper jsonMapper;
  private final CopyOnWriteArrayList<RestServerFilter> filters;

  @Override
  protected void initChannel(SocketChannel socketChannel) throws Exception {
    socketChannel.pipeline()
            .addLast(new HttpServerCodec(1024 * 4, 1024 * 8, 1024 * 16, false))// HTTP 服务的解码器
            .addLast(new HttpObjectAggregator(HulkConstants.MAX_FRAME_LENGTH))// HTTP 消息的合并处理
            .addLast(new RestHttResponseEncoder(invokerFactory, jsonMapper, filters))// 自定义编码器
            .addLast(new NettyRestHandler(invokerFactory, jsonMapper, filters)); // 逻辑处理
  }
}
